<template>
    <el-upload class="upload-demo" 
    :show-file-list="uploadProps.showFileList"
    drag 
    :http-request="upload"
    :action="host" 
    :disabled="uploadProps.disabled"
    :on-error="handleError"
    >
        <el-icon v-if="!uploadProps.disabled" class="el-icon--upload"><upload-filled /></el-icon>
        <div v-if="!uploadProps.disabled"  class="el-upload__text">
            将未生成附加包的zip拖曳到此处上传 或<em>点击选择未生成附加包的zip</em>
        </div>
        <el-progress v-else type="circle" :percentage="uploadProps.percentage"/>
    </el-upload>
    <el-checkbox v-model="uploadProps.creator.assetsAndData" label="生成资源文件和数据文件" size="large" />
    <el-checkbox v-model="uploadProps.creator.collision" label="生成碰撞箱文件" size="large" />
</template>
<script setup lang="ts">
import { UploadFilled } from '@element-plus/icons-vue'
import axios from 'axios';
import { ElMessage, UploadFile, UploadRequestOptions } from 'element-plus';
import { ref, reactive } from 'vue';
import { downloadStream } from '../utils/download';

const host = ref("http://localhost:9091/api/assets-and-data-creator/upload")
const uploadProps = reactive({
    showFileList: true,
    disabled: false,
    percentage: 0,
    creator:{
        assetsAndData: true,
        collision:true
    }
})

async function upload(options: UploadRequestOptions) {
    let params = new FormData();
    params.append("file", options.file)
    params.append("assetsAndData", uploadProps.creator.assetsAndData.toString())
    params.append("collision", uploadProps.creator.collision.toString())
    

    uploadProps.percentage = 25
    uploadProps.disabled = true
    const response = await axios.post("http://localhost:9091/api/assets-and-data-creator/upload", params, {responseType: "blob"})

        
    uploadProps.percentage=80
    // 从接口响应的header获取生成的文件名称（自定义的header）。
    let filename = response.headers['resource-filename']
    // 对文件名进行解码。
    filename = decodeURIComponent(filename);
    if (filename == undefined) filename = "test.zip"

    downloadStream(response.data, filename,"application/zip")
    
    uploadProps.percentage = 100
    uploadProps.disabled = false
}
function handleError(error: Error, uploadFile: UploadFile) {
    uploadProps.disabled = false
    ElMessage.error("提交失败"+error)
}
</script>

<style scoped>
.el-progress--circle {
    margin-right: 15px;
}
</style>